<template>
  <div class="lostfound-manage">
    <div class="header">
      <el-page-header @back="handleBack">
        <template #content>
          <span class="text-large font-600 mr-3">失物招领管理</span>
        </template>
      </el-page-header>
    </div>

    <div class="content">
      <el-card>
        <!-- 搜索和筛选区域 -->
        <template #header>
          <div class="table-header">
            <span>失物招领列表</span>
            <el-button type="primary" text :icon="Refresh" @click="loadItems">
              刷新
            </el-button>
          </div>
          
          <div class="search-filter-row">
            <el-form :model="searchForm" :inline="true" class="search-form">
              <el-form-item label="关键词">
                <el-input
                  v-model="searchForm.keyword"
                  placeholder="物品名称/描述"
                  clearable
                  style="width: 180px"
                />
              </el-form-item>
              
              <el-form-item label="分类筛选">
                <el-select v-model="searchForm.category" placeholder="全部分类" clearable style="width: 120px">
                  <el-option label="电子设备" value="电子设备" />
                  <el-option label="学习用品" value="学习用品" />
                  <el-option label="生活用品" value="生活用品" />
                  <el-option label="证件卡片" value="证件卡片" />
                  <el-option label="其他" value="其他" />
                </el-select>
              </el-form-item>

              <el-form-item label="状态">
                <el-select v-model="searchForm.status" placeholder="全部状态" clearable style="width: 120px">
                  <el-option label="待领取" :value="0" />
                  <el-option label="已领取" :value="1" />
                  <el-option label="已找到" :value="2" />
                  <el-option label="已认领" :value="3" />
                </el-select>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="handleSearch" :icon="Search">
                  搜索
                </el-button>
                <el-button @click="handleReset" :icon="RefreshLeft">
                  重置
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </template>

        <!-- 物品表格 -->
        <el-table
          :data="itemList"
          v-loading="loading"
          border
          style="width: 100%"
          empty-text="暂无失物招领数据"
        >
          <el-table-column type="expand" width="50">
            <template #default="props">
              <div class="item-detail">
                <el-descriptions :column="2" border>
                  <el-descriptions-item label="详细描述">
                    <div class="item-description">
                      {{ props.row.description || '暂无详细描述' }}
                    </div>
                  </el-descriptions-item>
                  <el-descriptions-item label="发布者信息">
                    <div class="user-info">
                      <span>{{ getPublisherName(props.row) }}</span>
                      <span class="user-id">(ID: {{ props.row.user_id || '未知' }})</span>
                      <div class="user-contact" v-if="getPublisherPhone(props.row)">
                        📞 {{ getPublisherPhone(props.row) }}
                      </div>
                    </div>
                  </el-descriptions-item>
                  <el-descriptions-item label="联系信息">
                    <div class="contact-info">
                      <p><strong>联系方式:</strong> {{ props.row.contact_info || '暂无联系方式' }}</p>
                    </div>
                  </el-descriptions-item>
                  <el-descriptions-item label="分类信息">
                    <div class="category-info">
                      <p><strong>物品分类:</strong> {{ props.row.category || '未分类' }}</p>
                    </div>
                  </el-descriptions-item>
                  <el-descriptions-item label="时间信息">
                    <div class="time-info">
                      <p><strong>创建时间:</strong> {{ formatDate(props.row.created_at) }}</p>
                      <p><strong>更新时间:</strong> {{ formatDate(props.row.updated_at) }}</p>
                    </div>
                  </el-descriptions-item>
                </el-descriptions>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="item_id" label="ID" width="60" align="center" />
          <el-table-column label="物品名称" min-width="200">
            <template #default="scope">
              <div class="item-name-cell">
                <span class="item-name">{{ scope.row.title || '未命名物品' }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="分类" width="100">
            <template #default="scope">
              <div class="category-cell">
                {{ scope.row.category || '未分类' }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="发布者" width="120">
            <template #default="scope">
              <div class="user-cell">
                {{ getPublisherName(scope.row) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="联系方式" width="150">
            <template #default="scope">
              <div class="contact-cell">
                {{ scope.row.contact_info || '暂无' }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="scope">
              <el-tag 
                :type="getStatusType(scope.row.status)"
                size="small"
                effect="light"
              >
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="发布时间" width="160">
            <template #default="scope">
              <div class="time-cell">
                {{ formatDate(scope.row.created_at) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" fixed="right" align="center">
            <template #default="scope">
              <div class="action-buttons">
                <el-button
                  type="danger"
                  size="small"
                  :icon="Delete"
                  @click="handleDelete(scope.row)"
                >
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Delete, RefreshLeft } from '@element-plus/icons-vue'
import { lostAndFoundApi } from '@/api/lostandfound'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const itemList = ref([])

const searchForm = reactive({
  keyword: '',
  category: '',
  status: ''
})

const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 方法
const loadItems = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      ...buildSearchParams()
    }

    console.log('请求失物招领参数:', params)

    const response = await lostAndFoundApi.list(params)
    console.log('失物招领响应:', response)

    if (response.code === 0) {
      itemList.value = response.data?.list || []
      pagination.total = response.data?.pagination?.total || 0
      
      // 调试数据
      console.log('处理后的数据:', itemList.value)
      if (itemList.value.length > 0) {
        console.log('第一条数据详情:', itemList.value[0])
        console.log('发布者信息:', itemList.value[0].publisher)
      }
      
      if (itemList.value.length === 0) {
        ElMessage.info('暂无失物招领数据')
      }
    } else {
      ElMessage.error(response.msg || '获取失物招领列表失败')
      itemList.value = []
    }
  } catch (error) {
    console.error('获取失物招领列表失败:', error)
    ElMessage.error('获取数据失败: ' + (error.message || '网络错误'))
    itemList.value = []
  } finally {
    loading.value = false
  }
}

// 获取发布者名称
const getPublisherName = (item) => {
  if (item.publisher) {
    return item.publisher.nickname || item.publisher.username || '未知用户'
  }
  return '未知用户'
}

// 获取发布者电话
const getPublisherPhone = (item) => {
  if (item.publisher) {
    return item.publisher.phone
  }
  return null
}

const buildSearchParams = () => {
  const params = {}
  
  // 关键词搜索 - 适配后端字段名
  if (searchForm.keyword) {
    params.title = searchForm.keyword
    params.description = searchForm.keyword
  }

  // 分类筛选 - 直接使用category字段进行精确匹配
  if (searchForm.category) {
    params.category = searchForm.category
  }

  // 状态筛选
  if (searchForm.status !== '') {
    params.status = searchForm.status
  }

  console.log('构建的搜索参数:', params)
  return params
}

const handleSearch = () => {
  pagination.page = 1
  loadItems()
}

const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    category: '',
    status: ''
  })
  pagination.page = 1
  loadItems()
}

const handleBack = () => {
  router.push('/admin/dashboard')
}

const handleDelete = async (item) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除"${item.title}"吗？此操作不可恢复。`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await lostAndFoundApi.delete(item.item_id)
    
    if (response.code === 0) {
      ElMessage.success('删除成功')
      loadItems()
    } else {
      ElMessage.error(response.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败: ' + (error.response?.data?.msg || error.message || '网络错误'))
    }
  }
}

const getStatusText = (status) => {
  const statusMap = {
    0: '待领取',
    1: '已领取',
    2: '已找到',
    3: '已认领'
  }
  return statusMap[status] || '未知状态'
}

const getStatusType = (status) => {
  const typeMap = {
    0: 'warning',  // 待领取 - 黄色
    1: 'success',  // 已领取 - 绿色
    2: 'success',  // 已找到 - 绿色
    3: 'success'   // 已认领 - 绿色
  }
  return typeMap[status] || 'info'
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  try {
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (error) {
    return dateString
  }
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.page = 1
  loadItems()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  loadItems()
}

// 生命周期
onMounted(() => {
  loadItems()
})
</script>

<style scoped>
.lostfound-manage {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.header {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.search-filter-row {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 4px;
  margin-top: 8px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: center;
}

.search-form .el-form-item {
  margin-bottom: 0;
}

.item-detail {
  padding: 16px;
}

.item-description {
  color: #606266;
  line-height: 1.5;
  padding: 8px 0;
  max-width: 400px;
}

.user-info {
  line-height: 1.5;
}

.user-id {
  color: #909399;
  font-size: 12px;
}

.user-contact {
  color: #409EFF;
  font-size: 12px;
  margin-top: 4px;
}

.contact-info {
  line-height: 1.5;
}

.contact-info p {
  margin: 4px 0;
}

.category-info {
  line-height: 1.5;
}

.category-info p {
  margin: 4px 0;
}

.time-info {
  line-height: 1.5;
}

.time-info p {
  margin: 4px 0;
  font-size: 13px;
  color: #606266;
}

.item-name-cell {
  display: flex;
  align-items: center;
}

.item-name {
  font-weight: 500;
  line-height: 1.4;
}

.category-cell {
  line-height: 1.4;
}

.user-cell {
  line-height: 1.4;
}

.contact-cell {
  line-height: 1.4;
  font-size: 12px;
}

.time-cell {
  font-size: 12px;
  color: #606266;
}

.action-buttons {
  display: flex;
  justify-content: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

:deep(.el-table__expanded-cell) {
  background: #fafafa;
}

:deep(.el-descriptions__body) {
  background: #fafafa;
}

:deep(.el-card__header) {
  padding-bottom: 8px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .search-form {
    gap: 8px;
  }
}

@media (max-width: 768px) {
  .lostfound-manage {
    padding: 10px;
  }
  
  .search-form {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>